package com.glsc.ngateway.oaflow.schedule;

import cn.hutool.core.util.StrUtil;
import com.glsc.ngateway.common.api.oaflow.dto.FixedincomeGDto;
import com.glsc.ngateway.common.base.domain.mysql.gateway.oaflow.TFixedincomeProcess;
import com.glsc.ngateway.common.base.domain.mysql.gateway.other.SystemConfig;
import com.glsc.ngateway.common.base.repo.mysql.gateway.other.SystemConfigRepository;
import com.glsc.ngateway.oaflow.constant.FixedIncomeConstant;
import com.glsc.ngateway.oaflow.service.FixedIncomeService;
import com.glsc.ngateway.oaflow.utils.DictConstant;
import com.xxl.job.core.handler.annotation.XxlJob;
import io.netty.util.internal.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class FixedIncomeTask {


    private static final Logger logger = LoggerFactory.getLogger(FixedIncomeTask.class);

    @Autowired
    FixedIncomeService fixedIncomeService;
    @Autowired
    RedisTemplate redisTemplate;
    @Resource
    private SystemConfigRepository systemConfigRepository;


    private List<String> getRealLeaderTripList(List<String> tripList) {
        List<String> realLeaderTripList = new ArrayList<>();
        SystemConfig config = systemConfigRepository.findByConfigCode(DictConstant.FIXED_TRIP_LIST_ACCOUNT);
        String tripConfig = config.getConfigValue();
        String[] tripConfigs = tripConfig.split(",");
        List<String> tripConfigList = Arrays.asList(tripConfigs);

        for (String user : tripList) {
            if (tripConfigList.contains(user)) {
                realLeaderTripList.add(user);
            }
        }
        return realLeaderTripList;
    }

    //5分钟 获取需要审批和正好处于出差状态的流程
    @XxlJob("fixedIncome_getBusinessTrip")
    //@Scheduled(cron = "0 0/5 * * * ?")
    public void getBusinessTrip() {
        SystemConfig config = systemConfigRepository.findByConfigCode(DictConstant.FIXINCOME_TASK_SCAN);
        if (config != null && "N".equals(config.getConfigValue())) {
            logger.info("固定收益任务未开启，不执行定时任务。");
            return;
        }

        logger.info("--------获取需要审批和正好处于出差状态的流程开始");
        String key = null;
        try {
            logger.info("衡泰移动审批获取key开始");
            key = (String) redisTemplate.opsForValue().get(FixedIncomeConstant.REDIS_FIXEDINCOME_KEY);
            if (StringUtil.isNullOrEmpty(key)) {
                key = fixedIncomeService.getKeyFromLogin();
                redisTemplate.opsForValue().set(FixedIncomeConstant.REDIS_FIXEDINCOME_KEY, key, 23, TimeUnit.HOURS);
            }
            logger.info("衡泰移动审批获取key结束。" + key);
        } catch (Exception e) {
            logger.error("衡泰移动审批获取key异常，有可能是redis的问题。", e);
            key = fixedIncomeService.getKeyFromLogin();
        }
        if (StringUtil.isNullOrEmpty(key)) {
            logger.error("衡泰移动审批获取key失败，返回结束。");
            return;
        }
        logger.info("调用衡泰接口获取领导出差状态开始");
        List<String> oriTripList = fixedIncomeService.getTripList(key);
        if (oriTripList != null && oriTripList.size() > 0) {
            if (oriTripList.size() == 1 && oriTripList.get(0).equals("error")) {
                logger.info("出差接口返回错误，定时任务什么也不做，结束。请查看！");
                return;
            }
        }
        logger.info("调用衡泰接口获取领导出差状态结束" + oriTripList.toString());

        List<String> tripList = getRealLeaderTripList(oriTripList);
        logger.info("真正领导为出差状态的是" + tripList.toString());

        if (tripList != null && tripList.size() > 0) {
            logger.info("有领导为出差状态，查询领导待办");
            //group 包含多笔交易，仅包含groupid，不能获取具体交易记录。所以需要再查询单笔交易
            List<FixedincomeGDto> groupList = fixedIncomeService.getGroupCode(key);
            if (groupList != null && groupList.size() > 0) {
                for (FixedincomeGDto group : groupList) {
                    logger.info("处理group");
                    fixedIncomeService.searchGroupTaskToDeal(tripList, group, key);
                }
            }
            logger.info("处理task");
            fixedIncomeService.searchTaskToDeal(tripList, key);

        } else {
            logger.info("无领导为出差状态，把oa未处理的流程做归档处理");
            //没有人员出差，需要把oa未处理的流程做归档处理
            List<TFixedincomeProcess> list = fixedIncomeService.findAllOaToDeal();
            if (list != null && list.size() > 0) {
                Set<String> set = list.stream().map(TFixedincomeProcess::getRequestId).collect(Collectors.toSet());
                for (String l : set) {
                    fixedIncomeService.doTaskOaForNoTrip(l);
                }
            }
        }
        logger.info("--------获取需要审批和正好处于出差状态的流程结束");
    }


    //同步oa状态到衡泰，定时任务
    //1分钟
    @XxlJob("fixedIncome_syncOaToFix")
    //@Scheduled(cron = "0 0/1 * * * ?")
    public void syncOaToFix() {
        SystemConfig config = systemConfigRepository.findByConfigCode(DictConstant.FIXINCOME_TASK_SCAN);
        if (config != null && "N".equals(config.getConfigValue())) {
            logger.info("固定收益任务未开启，不执行定时任务。");
            return;
        }
        logger.info("----------移动审批同步oa状态到衡泰开始");
        List<TFixedincomeProcess> oaDealList = fixedIncomeService.getProcessToDeal("0", "1");
        Set<String> agreeList = new HashSet<>();
        Set<String> rejectList = new HashSet<>();
        Set<String> rejectRequestIdList = new HashSet<>();

        Map<String, Set<String>> agreeListMap = new HashMap<>();
        Map<String, Set<String>> rejectListMap = new HashMap<>();
        Map<String, Set<String>> rejectRequestIdListMap = new HashMap<>();

        //oa处理了，衡泰没有处理，同步衡泰状态，调接口
        if (oaDealList != null && oaDealList.size() > 0) {
            for (TFixedincomeProcess oadeal : oaDealList) {
                if (oadeal.getStatus().equals("1")) {
                    if (agreeListMap.containsKey(oadeal.getUserId())) {
                        Set<String> agreeTmpList = agreeListMap.get(oadeal.getUserId());
                        agreeTmpList.add(oadeal.getNodeId());
                        agreeListMap.put(oadeal.getUserId(), agreeTmpList);
                    } else {
                        Set<String> agreeTmpList = new HashSet<>();
                        agreeTmpList.add(oadeal.getNodeId());
                        agreeListMap.put(oadeal.getUserId(), agreeTmpList);
                    }


                    //1 同意
                    //agreeList.add(oadeal.getNodeId());
                } else if (oadeal.getStatus().equals("2")) {
                    if (rejectListMap.containsKey(oadeal.getUserId())) {
                        Set<String> rejectTmpList = rejectListMap.get(oadeal.getUserId());
                        rejectTmpList.add(oadeal.getNodeId());
                        rejectListMap.put(oadeal.getUserId(), rejectTmpList);
                    } else {
                        Set<String> rejectTmpList = new HashSet<>();
                        rejectTmpList.add(oadeal.getNodeId());
                        rejectListMap.put(oadeal.getUserId(), rejectTmpList);
                    }
                    if (rejectRequestIdListMap.containsKey(oadeal.getUserId())) {
                        Set<String> rejectRequestIdTmpList = rejectRequestIdListMap.get(oadeal.getUserId());
                        rejectRequestIdTmpList.add(oadeal.getRequestId());
                        rejectRequestIdListMap.put(oadeal.getUserId(), rejectRequestIdTmpList);
                    } else {
                        Set<String> rejectRequestIdTmpList = new HashSet<>();
                        rejectRequestIdTmpList.add(oadeal.getRequestId());
                        rejectRequestIdListMap.put(oadeal.getUserId(), rejectRequestIdTmpList);
                    }

                    //2 拒绝
                    //rejectList.add(oadeal.getNodeId());
                    //rejectRequestIdList.add(oadeal.getRequestId());
                }
            }
            logger.info("agreeListMap:" + agreeListMap.toString());
            logger.info("rejectListMap:" + rejectListMap.toString());
            logger.info("rejectRequestIdListMap:" + rejectRequestIdListMap.toString());

            String key = null;
            try {
                logger.info("衡泰移动审批执行审批获取key开始");
                key = (String) redisTemplate.opsForValue().get(FixedIncomeConstant.REDIS_FIXEDINCOME_KEY);
                if (StrUtil.isEmpty(key)) {
                    key = fixedIncomeService.getKeyFromLogin();
                    redisTemplate.opsForValue().set(FixedIncomeConstant.REDIS_FIXEDINCOME_KEY, key, 23, TimeUnit.HOURS);
                }
                logger.info("衡泰移动审批执行审批获取key结束。" + key);
            } catch (Exception e) {
                logger.error("衡泰移动审批执行审批获取key异常，有可能是redis的问题。", e);
                key = fixedIncomeService.getKeyFromLogin();
            }
            if (agreeListMap != null && agreeListMap.size() > 0) {
                logger.info("移动审批同步oa状态到衡泰执行批准接口");
                //fixedIncomeService.doTask(String.join(",", agreeList), "1", key, null);

                for (Map.Entry<String, Set<String>> map : agreeListMap.entrySet()) {
                    fixedIncomeService.doTask(String.join(",", map.getValue()), "1", key, null, map.getKey());
                }
            }
            if (rejectListMap != null && rejectListMap.size() > 0) {
                logger.info("移动审批同步oa状态到衡泰执行拒绝接口");
                //fixedIncomeService.doTask(String.join(",", rejectList), "2", key, rejectRequestIdList);

                for (Map.Entry<String, Set<String>> map : rejectListMap.entrySet()) {
                    fixedIncomeService.doTask(String.join(",", map.getValue()), "2", key, rejectRequestIdListMap.get(map.getKey()), map.getKey());
                }
            }
        }
        logger.info("-----------移动审批同步oa状态到衡泰结束");
    }

    //同步衡泰状态到oa，定时任务
    //2分钟
    @XxlJob("fixedIncome_syncFixToOa")
    //@Scheduled(cron = "0 0/2 * * * ?")
    public void syncFixToOa() {
        SystemConfig config = systemConfigRepository.findByConfigCode(DictConstant.FIXINCOME_TASK_SCAN);
        if (config != null && "N".equals(config.getConfigValue())) {
            logger.info("固定收益任务未开启，不执行定时任务。");
            return;
        }
        logger.info("------------移动审批同步衡泰状态到oa开始");
        List<TFixedincomeProcess> oaDealList = fixedIncomeService.getProcessToDeal("1", "0");
        Set<String> agreeList = new HashSet<>();
        Set<String> rejectList = new HashSet<>();
        Set<String> oaSet = new HashSet<>();
        //oa没处理，衡泰处理了，同步oa状态，调oa归档接口
        if (oaDealList != null && oaDealList.size() > 0) {
            for (TFixedincomeProcess oadeal : oaDealList) {
                if (oadeal.getStatus().equals("1")) {
                    //除了1 都可视为拒绝
                    agreeList.add(oadeal.getNodeId());
                } else {
                    rejectList.add(oadeal.getNodeId());
                }
                oaSet.add(oadeal.getRequestId());
            }
            for (String oa : oaSet) {
                logger.info("移动审批同步衡泰状态到oa执行归档接口");
                fixedIncomeService.doTaskOa(oa, "1");
            }
        }
        logger.info("------------移动审批同步衡泰状态到oa结束");
    }
}